package cn.hxzy.user.controller;

import cn.hxzy.common.domain.School;
import cn.hxzy.common.domain.User;
import cn.hxzy.common.domain.UserClass;

import cn.hxzy.common.response.R;
import cn.hxzy.common.response.StatusEnum;
import cn.hxzy.common.domain.vo.UserLoginVo;
import cn.hxzy.user.service.UserService;
import cn.hxzy.common.util.AliOssUtil;
import cn.hxzy.common.util.ThreadLocalUtil;
import com.aliyun.oss.common.utils.HttpHeaders;
import com.aliyun.oss.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 项目名: education-platform
 * 当前用户: 18735
 * 创建日期: 2024/6/22 下午2:44
 * 项目介绍:
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param user 用户信息
     * @return jwt
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody @Valid UserLoginVo user, HttpServletResponse response) {
        String token = userService.login(user.getUsername(), user.getPassword());
        if(StringUtils.isNullOrEmpty(token)){
            return R.error(500,"用户名或密码错误",null);
        }
        return R.success(token);
    }

    @GetMapping("/select")
    public R<User> selectUserInfo() {
        User user = ThreadLocalUtil.getUser();
        return R.success(user);
    }
    @GetMapping("/selectUserInfo")
    private R<User> selectUserInfoa() {
        User user= userService.selectUserInfo();
        return R.success(user);
    }
    //修改密码
    @PutMapping("/updatePwd")
    public R updatePwd(@RequestBody Map map){

        int num=userService.updatePwd(map);
        if (num==-1){
            return R.success(500);
        }
        if (num==-2){
            return R.success(600);
        }
        return R.success(200);
    }


    //头像回显
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws Exception {
        //把文件的内容存储到本地磁盘上
        String originalFilename = file.getOriginalFilename();
        //保证文件的名字是唯一的,从而防止文件覆盖
        String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = AliOssUtil.uploadFile(filename,file.getInputStream());
        return R.success(url);
    }
    /**
     * 修改头像
     * @param userAvatar 头像
     * @return 影响行数
     */
    @PutMapping("/updatePic")
    public R<Integer>  updatePic(String userAvatar) {

        boolean update = userService.update(new UpdateWrapper<User>().
                eq("user_id", ThreadLocalUtil.getUser().getUserId())
                .set("user_avatar", userAvatar)
        );
        if (update){
            return R.success(1);
        }
        return R.error(505,"修改失败");
    }



    /**
     * 根据id查询用户信息
     * @return 用户信息
     */
    @GetMapping("/selectById")
    public R<User> select() {
        User user = userService.selectById();
        if (ObjectUtils.isEmpty(user)){
            R.error(1000,"用户不存在",null);
        }
        return R.success(user);
    }

    /**
     * 根据编号查询班级信息
     * @return 返回用户所对应的所有班级信息
     */
    @GetMapping("/selectClassById")
    public R<List<UserClass>> selectClassById() {
        List<UserClass> userClasses = userService.selectClassById();
        if (ObjectUtils.isEmpty(userClasses)){
            return R.error(1000,"用户不存在",null);
        }
        return R.success(userClasses);
    }

    /**
     * 修改用户信息
     * @param user 用戶信息
     * @return 影响行数
     */
    @PutMapping("/updateUser")
    public R<Boolean>  updateUserInfo(@RequestBody @Valid User user) {
        return userService.updateUser(user) ? R.success(true) : R.error(StatusEnum.SERVICE_ERROR);
    }

    /**
     * 获取验证码
     * @param userPhone 手机号
     * @return 验证码
     */
    @RequestMapping("/getCode/{userPhone}")
    public  R<String> getCode(
                        @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
                        @PathVariable String userPhone) {
        String code = userService.getCode(userPhone);
        if (StringUtils.isNullOrEmpty(code)) {
            return R.error(StatusEnum.SERVICE_ERROR.getCode(), "验证码发送失败", null);
        }
        return R.success(code);
    }

    /**
     * 验证码校验
     * @param captcha 输入的验证码
     * @return 验证码是否正确 1 正确
     */
    @RequestMapping("/loginBycode/{userPhone}/{captcha}")
    public R<Boolean> loginBycode(
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
            @PathVariable String userPhone,
            @NotEmpty
            @PathVariable String captcha,
            HttpServletResponse response) {
        //校验验证码
        String token = userService.loginByCode(userPhone, captcha);
        if (StringUtils.isNullOrEmpty(token)){
            return R.error(StatusEnum.SERVICE_ERROR);
        }
        response.setHeader(HttpHeaders.AUTHORIZATION, token);
        return R.success(true);
    }

    /**
     * 退出
     * @return 退出成功 / 失败
     */
    @RequestMapping("/logout")
    public R<String> logout() {
        return null;
    }

    /**
     * 删除
     * @return 删除成功 / 失败
     */
    @DeleteMapping("/deleteUser")
    public R<Boolean> deleteUser() {
        return R.success(true);
    }

    @PostMapping("/saveSchool")
    public R<Integer> saveSchool(@RequestBody School school) {
        return R.success(userService.save(school));
    }
}
